package com.melody.android.ui.activity

import android.annotation.SuppressLint
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.SeekBar
import android.widget.TextView
import com.melody.android.R
import com.melody.android.databinding.ActivitySongBinding
import com.melody.android.logic.LyricsManager
import com.melody.android.logic.model.Song
import com.melody.android.logic.util.Lyrics
import com.melody.android.logic.util.MediaPlayer
import java.util.*

class SongActivity : BaseActivity(), View.OnClickListener {

    private lateinit var binding: ActivitySongBinding   // 声明视图绑定变量
    private lateinit var selectedSong: Song             // 当前歌曲
    private lateinit var seekBar: SeekBar
    private lateinit var txtLyrics: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivitySongBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // 初始化视图及变量
        initView()

        // 显示歌曲播放进度
        showSongPlaybackProgress()
        // 显示歌词
        showLyrics()
    }

    /**
     * 初始化视图及变量
     */
    private fun initView() {
        // 初始化变量
        selectedSong = intent.getParcelableExtra("selectedSong")!!

        // 初始化视图
        seekBar = binding.seekBar
        txtLyrics = binding.txtLyrics

        // 基本视图逻辑(设置)
        binding.imgSongCover.setImageResource(selectedSong.cover)
        binding.txtIsPlayingSongName.text = selectedSong.name
        binding.imgPlayState.setImageResource(if (MediaPlayer.getPlaybackState()) R.drawable.ic_pause else R.drawable.ic_play)

        // 事件处理(若使用View.OnClickListener的形式则放在此处)
        binding.imgPlayState.setOnClickListener(this)
        binding.imgSongCover.setOnClickListener(this)
        binding.txtLyrics.setOnClickListener(this)
    }

    override fun onClick(view: View?) {
        when (view?.id) {
            binding.imgPlayState.id -> {
                binding.imgPlayState.setImageResource(if (MediaPlayer.getPlaybackState()) R.drawable.ic_play else R.drawable.ic_pause)
                MediaPlayer.pauseSong()
            }
            binding.imgSongCover.id -> {
                binding.imgSongCover.visibility = View.INVISIBLE
                binding.txtLyrics.visibility = View.VISIBLE
            }
            binding.txtLyrics.id -> {
                binding.txtLyrics.visibility = View.INVISIBLE
                binding.imgSongCover.visibility = View.VISIBLE
            }
        }
    }

    /**
     * 显示歌曲播放进度
     */
    private fun showSongPlaybackProgress() {
        // 播放进度条和时间显示
        seekBar.max = MediaPlayer.getSongDuration()
        seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                // 如果进度值是由用户触发的, 则设置歌曲的播放进度
                if (fromUser) {
                    MediaPlayer.seekTo(progress)
                    updateTimeText(progress)
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
                // 此处代码不能为空
                Log.d("SongActivity", "Start tracking touch")
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                // 获取当前seekBar的进度值
                val progress = seekBar?.progress ?: 0
                // 更新歌曲的播放进度
                MediaPlayer.seekTo(progress)
                // 更新歌曲的时间显示
                updateTimeText(progress)
            }
        })

        // 使用定时器更新播放器进度条
        val timer = Timer()
        timer.scheduleAtFixedRate(object : TimerTask() {
            override fun run() {
                runOnUiThread {
                    seekBar.progress = MediaPlayer.getSongCurrentPosition()
                    updateTimeText(MediaPlayer.getSongCurrentPosition())
                }
            }
        }, 0, 100)
    }

    /**
     * 更新歌曲时间显示
     * @param progress 歌曲播放进度
     */
    @SuppressLint("SetTextI18n")
    private fun updateTimeText(progress: Int) {
        val currentSeconds = progress / 1000
        val durationSeconds = MediaPlayer.getSongDuration() / 1000
        val currentTime = String.format("%02d:%02d", currentSeconds / 60, currentSeconds % 60)
        val durationTime = String.format("%02d:%02d", durationSeconds / 60, durationSeconds % 60)
        binding.txtSongTime.text = "$currentTime / $durationTime"
    }

    /**
     * 显示歌词
     */
    private fun showLyrics() {
        val lyricsText =  Lyrics.loadLyrics(selectedSong.name)
        val lyricsDisplayListener = object : LyricsManager.LyricsDisplayListener {
            override fun onSelectedLyricsUpdate(lyricsText: CharSequence) {
                runOnUiThread {
                    txtLyrics.text = lyricsText
                }
            }

            override fun onScrollToLine(currentLineIndex: Int) {
                val scrollY = txtLyrics.lineHeight * currentLineIndex
                txtLyrics.scrollTo(0, scrollY)
            }
        }

        Lyrics.parseAndDisplayLyrics(lyricsDisplayListener, lyricsText)
        Lyrics.startUpdatingLyrics()
    }

}